package com.osilon;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.jar.JarFile;

import com.osilon.updater.Updater;
import com.osilon.util.ClassCache;


public class OsilonClassLoader extends ClassLoader {
	private File jar = new File("minecraft_server.jar");
	private ClassCache cache;
	
	public OsilonClassLoader(){
		try {
			cache = new ClassCache(new JarFile(jar));
			Updater updater = new Updater(cache);
			updater.update();
		} catch(IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public URL getResource(String name) {
		try {
			return new URL("jar:" + jar.toURI().toURL() + "!/" + name);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	@Override
	public Class<?> loadClass(String name) throws ClassNotFoundException {
		Class<?> c = null;
		
		try {
			c = super.findSystemClass(name);
		} catch(ClassNotFoundException e) {
			byte[] buffer = cache.getCode(name);
			c = super.defineClass(name, buffer, 0, buffer.length);
		}
		
		if(c != null)
			return c;
		else return super.loadClass(name);
	}
}
